package com.kakarote.oa.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.util.TypeUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kakarote.common.field.utils.FieldUtil;
import com.kakarote.core.common.Const;
import com.kakarote.core.common.enums.FieldEnum;
import com.kakarote.core.common.enums.SystemCodeEnum;
import com.kakarote.core.exception.CrmException;
import com.kakarote.core.servlet.ApplicationContextHolder;
import com.kakarote.core.servlet.BaseServiceImpl;
import com.kakarote.core.utils.UserCacheUtil;
import com.kakarote.oa.common.LanguageFieldUtil;
import com.kakarote.oa.common.OaCodeEnum;
import com.kakarote.oa.entity.BO.OaFieldVerifyBO;
import com.kakarote.oa.entity.PO.OaLogData;
import com.kakarote.oa.entity.PO.OaLogTemplateConfig;
import com.kakarote.oa.entity.PO.OaLogTemplateField;
import com.kakarote.oa.entity.VO.OaLogTemplateFieldVO;
import com.kakarote.oa.mapper.OaLogTemplateFieldMapper;
import com.kakarote.oa.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author wanli
 * 针对表【wk_oa_log_template_field(市场活动字段信息表)】的数据库操作Service实现
 * @date 2022-07-04 18:07:03
 */
@Service
public class OaLogTemplateFieldServiceImpl extends BaseServiceImpl<OaLogTemplateFieldMapper, OaLogTemplateField> implements IOaLogTemplateFieldService {

    @Autowired
    private IOaLogTemplateFieldExtendService oaLogTemplateFieldExtendService;

    @Autowired
    private IOaLogDataService oaLogTemplateDataService;

    @Autowired
    private IOaLogFieldConfigService oaLogFieldConfigService;

    @Autowired
    private IOaLogTemplateConfigService oaLogTemplateConfigService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveField(Long configId, List<OaLogTemplateField> fieldList) {

        //防止删除所有字段
        if (fieldList.isEmpty()) {
            throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
        }
        //字段不能超过100个
        if (fieldList.size() > Const.QUERY_MAX_SIZE) {
            throw new CrmException(OaCodeEnum.CRM_FIELD_NUM_ERROR);
        }

        long nameCount = fieldList.stream().filter(data -> !Objects.equals(data.getType(), FieldEnum.DESC_TEXT.getType())).map(OaLogTemplateField::getName).distinct().count();

        //描述文字类型字段名称可以重复
        long fieldSize = fieldList.stream().filter(data -> !Objects.equals(data.getType(), FieldEnum.DESC_TEXT.getType())).count();
        if (fieldSize != nameCount) {
            throw new CrmException(OaCodeEnum.THE_FIELD_NAME_OF_THE_FORM_CANNOT_BE_REPEATED);
        }
        long tagCount = fieldList.stream().filter(crmField -> FieldEnum.TAG.getType().equals(crmField.getType())).distinct().count();
        //标签类型字段只允许出现一个
        if (tagCount > 1) {
            throw new CrmException(OaCodeEnum.CRM_TAG_FIELD_REPETITION_ERROR);
        }
        List<Long> fieldIds = new ArrayList<>();
        //数据处理
        fieldList.forEach(crmField -> {
            //关于非隐藏字段的判断
            if (crmField.getIsHidden().equals(1)) {
                if (crmField.getIsNull() == 1) {
                    throw new CrmException(OaCodeEnum.REQUIRED_OPTIONS_CANNOT_BE_HIDDEN);
                }
            }
            //判断数字格式限制的小数位数是否正确
            if (FieldUtil.equalsByType(crmField.getType(), FieldEnum.NUMBER, FieldEnum.FLOATNUMBER, FieldEnum.PERCENT)) {
                if (FieldUtil.verifyStrForNumRestrict(crmField.getMaxNumRestrict(), crmField.getMinNumRestrict())) {
                    throw new CrmException(OaCodeEnum.THE_FIELD_NUM_RESTRICT_ERROR);
                }
            }
            //判断明细表格的数据是否正确
            if (FieldEnum.DETAIL_TABLE.getType().equals(crmField.getType())) {
                if (CollUtil.isEmpty(crmField.getFieldExtendList())) {
                    throw new CrmException(OaCodeEnum.THE_FIELD_DETAIL_TABLE_FORMAT_ERROR);
                }
            }
            String registerTime = "创建时间";
            if (registerTime.equals(crmField.getName())) {
                throw new CrmException(OaCodeEnum.THE_FIELD_NAME_OF_THE_FORM_CANNOT_BE_REPEATED);
            }
            //处理单选和多选等的setting
            /*
             多选和单选  [{"id":"",value:""}] id是选项id，value是选项值
             关注度字段 [{"num":"1","value":"1"}]   超过num天未跟进，减少value颗星
             标签字段  [{"name":"标签分组名称","labelList":[{"name":"标签名称","color":"#000300"}]}]
                      name 标签分组名称 labelList   标签列表  name  标签名称  color 标签颜色
             自动编号字段 [{"type":1,"value":“1”,"textFormat":"","startNumber":100000,"stepNumber":1000,"resetType":1}]
             type 1 自动计数 2 固定值 3 表单内字段
             value 当type为2时，为固定的值，当type为3时，展示fieldName
             textFormat  当type为3，并且为日期和日期时间类型时需要，为需要格式化的日期格式
             startNumber 当type为1时需要，起始编号
             stepNumber  当type为1时需要，递增数
             resetType   当type为1时需要，1 每天 2 每月 3 每年 4 从不
            */
            if (FieldUtil.equalsByType(crmField.getType(), FieldEnum.TAG, FieldEnum.ATTENTION)) {
                if (crmField.getSetting() != null && !crmField.getSetting().isEmpty()) {
                    crmField.setOptions(JSON.toJSONString(crmField.getSetting()));
                }
            }
            crmField.setConfigId(configId);
            if (crmField.getFieldId() != null) {
                fieldIds.add(crmField.getFieldId());
            }
        });
        //查询需要删除的
        List<OaLogTemplateField> allFieldList = lambdaQuery().eq(OaLogTemplateField::getConfigId, configId).list();
        for (OaLogTemplateField field : allFieldList) {
            String cover = Integer.toBinaryString(1 << 8).substring(1);
            String s = Integer.toBinaryString(field.getOperating());
            String num = s.length() < 8 ? cover.substring(s.length()) + s : s;

            //校验不允许删除字段的删除操作
            if (!fieldIds.contains(field.getFieldId())) {
                char i = num.charAt(1);
                if (i == 0) {
                    throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
                }
            }
            //校验不允许隐藏的字段
            char isHidden = num.charAt(7);
            if (isHidden == 0 && Objects.equals(1, field.getIsHidden())) {
                throw new CrmException(SystemCodeEnum.SYSTEM_NO_VALID);
            }
        }
        allFieldList.removeIf(crmField -> fieldIds.contains(crmField.getFieldId()));
        //不在上面循环,避免一些不可恢复的数据
        for (OaLogTemplateField field : allFieldList) {
            if (!Objects.equals(0, field.getFieldType())) {
                continue;
            }
            //删除自定义字段
            if (FieldEnum.DETAIL_TABLE.getType().equals(field.getType())) {
                oaLogTemplateFieldExtendService.deleteCrmFieldExtend(field.getFieldId());
            }
            removeById(field.getFieldId());
            // TODO  清理日志實體類擴展字段表
            oaLogTemplateDataService.lambdaUpdate().eq(OaLogData::getFieldId, field.getFieldId()).remove();

        }

        //保存
        AtomicInteger sort = new AtomicInteger(0);
        List<OaLogTemplateField> serialNumberField = new ArrayList<>();
        Map<String, OaLogTemplateField> name2field = new HashMap<>();
        fieldList.forEach(field -> {

            field.setSorting(sort.getAndIncrement());
            if (ObjectUtil.isEmpty(field.getDefaultValue())) {
                field.setDefaultValue("");
            } else {
                boolean isNeedHandle = FieldUtil.equalsByType(field.getType(), FieldEnum.AREA, FieldEnum.AREA_POSITION, FieldEnum.CURRENT_POSITION);
                if (isNeedHandle) {
                    field.setDefaultValue(JSON.toJSONString(field.getDefaultValue()));
                }
                if (field.getDefaultValue() instanceof Collection) {
                    field.setDefaultValue(StrUtil.join(Const.SEPARATOR, field.getDefaultValue()));
                }
            }

            if (field.getFieldId() != null) {
                if (FieldEnum.DETAIL_TABLE.getType().equals(field.getType())) {
                    oaLogTemplateFieldExtendService.saveOrUpdateCrmFieldExtend(field.getFieldExtendList(), field.getFieldId(), true);
                }
                // 获取当前时间
                field.setUpdateTime(LocalDateTime.now());
                updateById(field);
            } else {
                List<String> fieldNameList = this.lambdaQuery()
                        .select(OaLogTemplateField::getFieldName)
                        .eq(OaLogTemplateField::getConfigId, configId)
                        .list()
                        .stream()
                        .map(OaLogTemplateField::getFieldName)
                        .map(StrUtil::toUnderlineCase)
                        .collect(Collectors.toList());
                String nextFieldName = oaLogFieldConfigService.getNextFieldName(configId, field.getType(), fieldNameList, Const.AUTH_DATA_RECURSION_NUM);
                field.setFieldName(nextFieldName);
                save(field);
                if (FieldEnum.DETAIL_TABLE.getType().equals(field.getType())) {
                    oaLogTemplateFieldExtendService.saveOrUpdateCrmFieldExtend(field.getFieldExtendList(), field.getFieldId(), false);
                }
            }
            if (FieldEnum.SERIAL_NUMBER.getType().equals(field.getType())) {
                serialNumberField.add(field);
            } else {
                name2field.put(field.getName(), field);
            }
        });
        OaLogTemplateField map = new OaLogTemplateField();
        map.setFieldName("createTime");
        map.setType(13);
        name2field.put("创建时间", map);
        for (OaLogTemplateField crmField : serialNumberField) {
            List<OaLogFieldNumberDataServiceImpl.FieldNumberSetting> numberSettings = crmField.getSetting().stream().map(data -> BeanUtil.copyProperties(data, OaLogFieldNumberDataServiceImpl.FieldNumberSetting.class)).collect(Collectors.toList());
            numberSettings.removeIf(data -> 3 == data.getType() && !name2field.containsKey(data.getValue()));
            for (OaLogFieldNumberDataServiceImpl.FieldNumberSetting numberSetting : numberSettings) {
                if (3 == numberSetting.getType()) {
                    OaLogTemplateField field = name2field.get(numberSetting.getValue());
                    numberSetting.setValue(field.getFieldName());
                    if (field.getType() != 4 && field.getType() != 13 && StrUtil.isNotEmpty(numberSetting.getTextFormat())) {
                        numberSetting.setTextFormat("");
                    }
                }
            }
            lambdaUpdate().set(OaLogTemplateField::getOptions, JSON.toJSONString(numberSettings)).set(OaLogTemplateField::getUpdateTime, DateUtil.date()).eq(OaLogTemplateField::getFieldId, crmField.getFieldId()).update();
        }
    }

    @Override
    public List<OaLogTemplateFieldVO> queryField(Long configId, Long logId) {
        return queryField(configId, logId, false);
    }

    @Override
    public List<OaLogTemplateFieldVO> queryActivityFields() {
        return getBaseMapper().queryActivityFields();
    }

    /**
     * 日志列表查询日志字段列表
     *
     * @param categoryIds ids
     * @return data
     * @author zhangzhiwei
     */
    @Override
    public Map<Long, List<OaLogTemplateFieldVO>> queryConfigMap(List<Long> categoryIds) {

        List<OaLogTemplateField> crmFieldList = this.lambdaQuery()
                .in(OaLogTemplateField::getConfigId, categoryIds)
                .eq(OaLogTemplateField::getIsHidden, 0)
                .orderByAsc(OaLogTemplateField::getSorting)
                .list();
        Map<Long, List<OaLogTemplateFieldVO>> listMap = crmFieldList.stream().map(field -> {
            OaLogTemplateFieldVO crmModelFiled = BeanUtil.copyProperties(field, OaLogTemplateFieldVO.class);
            FieldEnum typeEnum = FieldEnum.parse(crmModelFiled.getType());
            recordToFormType(crmModelFiled, typeEnum);
            return crmModelFiled;
        }).collect(Collectors.groupingBy(OaLogTemplateFieldVO::getConfigId));
        for (List<OaLogTemplateFieldVO> value : listMap.values()) {
            if (value.size() > 3) {
                CollUtil.sub(value, 0, 3);
            }
        }
        return listMap;
    }


    @Override
    public List<OaLogTemplateFieldVO> information(Long id, Long categoryId) {
        return queryField(categoryId, id, true);
    }

    private List<OaLogTemplateFieldVO> queryField(Long configId, Long logId, Boolean appendInformation) {
        JSONObject logEntity = new JSONObject();
        if (ObjectUtil.isNotNull(logId)) {
            logEntity = ApplicationContextHolder.getBean(IOaLogService.class).queryById(logId);
        }
        Integer type = 0;
        OaLogTemplateConfig oaLogTemplateConfig = oaLogTemplateConfigService.getById(configId);
        if (ObjectUtil.isNotEmpty(oaLogTemplateConfig)) {
            type = oaLogTemplateConfig.getType();
        }
        List<OaLogTemplateField> crmFieldList = this.lambdaQuery()
                .eq(OaLogTemplateField::getConfigId, configId)
                .eq(OaLogTemplateField::getIsHidden, 0)
                .orderByAsc(OaLogTemplateField::getSorting)
                .list();
        JSONObject finalLogEntity = logEntity;
        List<OaLogTemplateFieldVO> fieldList = crmFieldList.stream().map(field -> {
            OaLogTemplateFieldVO crmModelFiled = BeanUtil.copyProperties(field, OaLogTemplateFieldVO.class);
            FieldEnum typeEnum = FieldEnum.parse(crmModelFiled.getType());
            String fieldName = StrUtil.toCamelCase(crmModelFiled.getFieldName());
            if (ObjectUtil.isNotNull(logId)) {
                Object value = finalLogEntity.get(fieldName);
                if (ObjectUtil.isEmpty(value)) {
                    crmModelFiled.setValue(null);
                } else {
                    Object dataValue = FieldUtil.format2Object(value, typeEnum);
                    crmModelFiled.setValue(dataValue);
                }
            }
            recordToFormType(crmModelFiled, typeEnum);
            return crmModelFiled;
        }).collect(Collectors.toList());
        if (appendInformation) {
            List<OaLogTemplateFieldVO> modelFiledVOS = appendInformation(logEntity);
            fieldList.addAll(modelFiledVOS);
        }
        for (OaLogTemplateFieldVO fieldVO : fieldList) {
            Map<String, String> keyMap = new HashMap<>();
            keyMap.put("name_resourceKey", "oa.log.template.field." + type + "." + LanguageFieldUtil.getFieldName(fieldVO.getFieldName()));
            fieldVO.setLanguageKeyMap(keyMap);
        }
        return fieldList;
    }

    private List<OaLogTemplateFieldVO> appendInformation(JSONObject crmModel) {
        List<OaLogTemplateFieldVO> filedVOS = new ArrayList<>();
        Object value = UserCacheUtil.getSimpleUsers(Collections.singletonList((Long) crmModel.get("createUserId")));
        filedVOS.add(new OaLogTemplateFieldVO("create_user_name", FieldEnum.USER, "创建人", 1).setValue(value));
        filedVOS.add(new OaLogTemplateFieldVO("create_time", FieldEnum.DATETIME, "创建时间", 1).setValue(crmModel.get("createTime")));
        filedVOS.add(new OaLogTemplateFieldVO("update_time", FieldEnum.DATETIME, "更新时间", 1).setValue(crmModel.get("updateTime")));
        for (OaLogTemplateFieldVO filedVO : filedVOS) {
            filedVO.setSysInformation(1);
        }
        return filedVOS;
    }

    /**
     * 保存自定义字段列表
     *
     * @param configId    configId
     * @param isQueryHide 是否查询隐藏字段
     * @return data
     */
    @Override
    public List<OaLogTemplateField> list(Long configId, boolean isQueryHide) {
        QueryWrapper<OaLogTemplateField> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("config_id", configId);
        if (!isQueryHide) {
            queryWrapper.eq("is_hidden", 0);
        }
        queryWrapper.orderByAsc("sorting");
        List<OaLogTemplateField> fieldList = list(queryWrapper);
        Map<String, String> map = fieldList.stream().collect(Collectors.toMap(OaLogTemplateField::getFieldName, OaLogTemplateField::getName));
        map.put("createTime", "创建时间");
        fieldList.forEach(field -> recordToFormType2(map, field, FieldEnum.parse(field.getType())));
        return fieldList;
    }

    @Override
    public List<List<OaLogTemplateField>> queryFormPositionField(Long configId, boolean isQueryHide) {
        List<OaLogTemplateField> fieldList = this.list(configId, isQueryHide);
        if (CollectionUtil.isNotEmpty(fieldList)) {
            for (OaLogTemplateField field : fieldList) {
                Map<String, String> keyMap = new HashMap<>();
                keyMap.put("name_resourceKey", "oa.log.template.field." + LanguageFieldUtil.getFieldName(field.getFieldName()));
                field.setLanguageKeyMap(keyMap);
            }
        }
        return FieldUtil.convertFormPositionFieldList(fieldList, OaLogTemplateField::getXAxis, OaLogTemplateField::getYAxis, OaLogTemplateField::getSorting);
    }

    @Override
    public List<List<OaLogTemplateFieldVO>> queryFormPositionFieldVO(Long configId, Long logId) {
        List<OaLogTemplateFieldVO> list = this.queryField(configId, logId);
        return FieldUtil.convertFormPositionFieldList(list, OaLogTemplateFieldVO::getXAxis, OaLogTemplateFieldVO::getYAxis, OaLogTemplateFieldVO::getSorting);
    }

    private List<Object> parseArray(Object content, FieldEnum fieldEnum) {
        if (content == null) {
            return Collections.emptyList();
        }
        if (content instanceof String) {
            try {
                if (fieldEnum == FieldEnum.CHECKBOX || fieldEnum == FieldEnum.SELECT) {
                    return new ArrayList<>(StrUtil.splitTrim((String) content, Const.SEPARATOR));
                }
                return JSON.parseArray((String) content);
            } catch (JSONException exception) {
                return Collections.emptyList();
            }
        }
        return Collections.emptyList();
    }

    @Override
    public void recordToFormType(OaLogTemplateFieldVO record, FieldEnum typeEnum) {
        record.setFormType(typeEnum.getFormType());
        switch (typeEnum) {
            case ATTENTION:
                if (record.getDefaultValue() == null) {
                    record.setDefaultValue(0);
                } else {
                    record.setDefaultValue(TypeUtils.castToInt(record.getDefaultValue()));
                }
                if (record.getValue() == null) {
                    record.setValue(0);
                } else {
                    record.setValue(TypeUtils.castToInt(record.getValue()));
                }
            case SERIAL_NUMBER:
                record.setSetting(parseArray(record.getOptions(), typeEnum));
                break;
            case TAG:
            case CHECKBOX:
                record.setDefaultValue(parseArray(record.getDefaultValue(), typeEnum));
                record.setValue(parseArray(record.getValue(), typeEnum));
            case SELECT:
                if (Objects.equals(record.getRemark(), FieldEnum.OPTIONS_TYPE.getFormType())) {
                    if (CollUtil.isEmpty(record.getOptionsData())) {
                        JSONObject optionsData = JSON.parseObject(record.getOptions());
                        record.setOptionsData(optionsData);
                        record.setSetting(new ArrayList<>(optionsData.keySet()));
                    }
                } else {
                    if (CollUtil.isEmpty(record.getSetting())) {
                        record.setSetting(parseArray(record.getOptions(), typeEnum));
                    }
                }
                break;
            case DATE_INTERVAL:
                record.setDefaultValue(StrUtil.split((String) record.getDefaultValue(), Const.SEPARATOR));
                if (record.getValue() instanceof String) {
                    record.setValue(StrUtil.split((String) record.getValue(), Const.SEPARATOR));
                }
                break;
            case USER:
            case STRUCTURE:
                record.setDefaultValue(new ArrayList<>(0));
                break;
            case AREA:
            case AREA_POSITION:
            case CURRENT_POSITION:
                String defaultValue = Optional.ofNullable(record.getDefaultValue()).orElse("").toString();
                record.setDefaultValue(JSON.parse(defaultValue));
                if (record.getValue() instanceof String) {
                    String value = Optional.ofNullable(record.getValue()).orElse("").toString();
                    record.setValue(JSON.parse(value));
                }
                break;
            case DETAIL_TABLE:
                if (CollUtil.isEmpty(record.getFieldExtendList())) {
                    record.setFieldExtendList(oaLogTemplateFieldExtendService.queryCrmFieldExtend(record.getFieldId()));
                }
                break;
            case DESC_TEXT:
                record.setValue(record.getDefaultValue());
                break;
            default:
                record.setSetting(new ArrayList<>());
                break;
        }
    }

    @Override
    public List<OaLogTemplateFieldVO> queryExportFields(Long categoryId) {
        List<OaLogTemplateFieldVO> allFields = this.queryField(categoryId, null);
        allFields.removeIf(fieldSort -> FieldUtil.equalsByType(fieldSort.getType(), FieldEnum.DESC_TEXT, FieldEnum.DETAIL_TABLE, FieldEnum.FIELD_GROUP));
        allFields.add(new OaLogTemplateFieldVO(0L, "category", "日志类型", FieldEnum.TEXT, 1));
        allFields.add(new OaLogTemplateFieldVO(1L, "createTime", "创建日期", FieldEnum.DATETIME, 1));
        allFields.add(new OaLogTemplateFieldVO(2L, "createUserName", "创建人", FieldEnum.TEXT, 1));
        allFields.add(new OaLogTemplateFieldVO(3L, "sendName", "发送给", FieldEnum.TEXT, 1));
        allFields.add(new OaLogTemplateFieldVO(4L, "relateCrmWork", "关联业务", FieldEnum.TEXT, 1));
        allFields.add(new OaLogTemplateFieldVO(5L, "comment", "回复", FieldEnum.TEXT, 1));
        return allFields;
    }

    @Override
    public OaFieldVerifyBO verify(OaFieldVerifyBO verifyBO) {
        OaLogTemplateField field = getById(verifyBO.getFieldId());
        Long configId = field.getConfigId();
        int count;
        if (field.getFieldType().equals(1)) {
            count = getBaseMapper().verifyFixedField(field.getFieldName(), verifyBO.getValue().trim(), verifyBO.getDataId(), configId);
        } else {
            count = getBaseMapper().verifyCustomField(StrUtil.toCamelCase(field.getFieldName()), verifyBO.getValue().trim(), verifyBO.getDataId());
        }
        if (count < 1) {
            verifyBO.setStatus(1);
        }
        return verifyBO;
    }

    private void recordToFormType2(Map<String, String> fieldMap, OaLogTemplateField record, FieldEnum typeEnum) {
        record.setFormType(typeEnum.getFormType());
        switch (typeEnum) {
            case ATTENTION:
                if (record.getDefaultValue() == null) {
                    record.setDefaultValue(0);
                } else {
                    record.setDefaultValue(TypeUtils.castToInt(record.getDefaultValue()));
                }
            case SERIAL_NUMBER:
                List<Object> objects = parseArray(record.getOptions(), typeEnum);
                for (Object object : objects) {
                    if (object instanceof JSONObject) {
                        JSONObject map = (JSONObject) object;
                        if (Objects.equals(3, map.get("type")) && map.containsKey("value")) {
                            map.put("value", fieldMap.get(map.getString("value")));
                        }
                    }
                }
                record.setSetting(objects);
                break;
            case TAG:
            case CHECKBOX:
                record.setDefaultValue(parseArray(record.getDefaultValue(), typeEnum));
            case SELECT:
                if (Objects.equals(record.getRemark(), FieldEnum.OPTIONS_TYPE.getFormType())) {
                    JSONObject optionsData = JSON.parseObject(record.getOptions(), Feature.OrderedField);
                    record.setOptionsData(optionsData);
                    record.setSetting(new ArrayList<>(optionsData.keySet()));
                } else {
                    record.setSetting(parseArray(record.getOptions(), typeEnum));
                }
                break;
            case DATE_INTERVAL:
                String dataValueStr = Optional.ofNullable(record.getDefaultValue()).orElse("").toString();
                record.setDefaultValue(StrUtil.split(dataValueStr, Const.SEPARATOR));
                break;
            case USER:
            case STRUCTURE:
                record.setDefaultValue(new ArrayList<>(0));
                break;
            case AREA:
            case AREA_POSITION:
            case CURRENT_POSITION:
                String defaultValue = Optional.ofNullable(record.getDefaultValue()).orElse("").toString();
                record.setDefaultValue(JSON.parse(defaultValue));
                break;
            case DETAIL_TABLE:
                record.setFieldExtendList(oaLogTemplateFieldExtendService.queryCrmFieldExtend(record.getFieldId()));
                break;
            default:
                record.setSetting(new ArrayList<>());
                break;
        }
    }


    private void recordToFormType2(OaLogTemplateFieldVO record, FieldEnum typeEnum) {
        record.setFormType(typeEnum.getFormType());
        switch (typeEnum) {
            case ATTENTION:
                if (record.getDefaultValue() == null) {
                    record.setDefaultValue(0);
                } else {
                    record.setDefaultValue(TypeUtils.castToInt(record.getDefaultValue()));
                }
                if (record.getValue() == null) {
                    record.setValue(0);
                } else {
                    record.setValue(TypeUtils.castToInt(record.getValue()));
                }
            case SERIAL_NUMBER:
                record.setSetting(parseArray(record.getOptions(), typeEnum));
                break;
            case TAG:
            case CHECKBOX:
                record.setDefaultValue(parseArray1(record.getDefaultValue(), typeEnum));
                record.setValue(parseArray(record.getValue(), typeEnum));
            case SELECT:
                if (Objects.equals(record.getRemark(), FieldEnum.OPTIONS_TYPE.getFormType())) {
                    if (CollUtil.isEmpty(record.getOptionsData())) {
                        JSONObject optionsData = JSON.parseObject(record.getOptions());
                        record.setOptionsData(optionsData);
                        record.setSetting(new ArrayList<>(optionsData.keySet()));
                    }
                } else {
                    if (CollUtil.isEmpty(record.getSetting())) {
                        record.setSetting(parseArray(record.getOptions(), typeEnum));
                    }
                }
                break;
            case DATE_INTERVAL:
                String dataValueStr = Optional.ofNullable(record.getDefaultValue()).orElse("").toString();
                if (StrUtil.isNotEmpty(dataValueStr)) {
                    record.setDefaultValue(parseArray(dataValueStr, typeEnum));
                } else {
                    record.setDefaultValue(new ArrayList<>());
                }
                break;
            case USER:
            case STRUCTURE:
                record.setDefaultValue(new ArrayList<>(0));
                break;
            case AREA:
            case AREA_POSITION:
            case CURRENT_POSITION:
                String defaultValue = Optional.ofNullable(record.getDefaultValue()).orElse("").toString();
                record.setDefaultValue(JSON.parse(defaultValue));
                if (record.getValue() instanceof String) {
                    String value = Optional.ofNullable(record.getValue()).orElse("").toString();
                    record.setValue(JSON.parse(value));
                }
                break;
            case DETAIL_TABLE:
                if (CollUtil.isEmpty(record.getFieldExtendList())) {
                    record.setFieldExtendList(oaLogTemplateFieldExtendService.queryCrmFieldExtend(record.getFieldId()));
                }
                break;
            case DESC_TEXT:
                record.setValue(record.getDefaultValue());
                break;
            default:
                record.setSetting(new ArrayList<>());
                break;
        }
    }

    private List<Object> parseArray1(Object content, FieldEnum fieldEnum) {
        if (content == null) {
            return Collections.emptyList();
        }
        if (content instanceof String) {
            try {
                if (fieldEnum == FieldEnum.SELECT) {
                    return new ArrayList<>(StrUtil.splitTrim((String) content, Const.SEPARATOR));
                }
                return JSON.parseArray((String) content);
            } catch (JSONException exception) {
                return Collections.emptyList();
            }
        }
        return Collections.emptyList();
    }

}




